package com.tianji.memory;

import cn.hutool.json.JSONUtil;
import com.tianji.common.utils.CollUtils;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class RedisChatMemory implements ChatMemory {

    //定义一个key前缀
    private static final String CHAT_MEMORY_KEY_PREFIX = "chat:memory:";
    //定义prefix

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void add(String conversationId, List<Message> messages) {
        //1. 健壮性校验
        if(CollUtils.isEmpty(messages)){
            //如果消息为空，则直接返回
            return;
        }
        // 使用 List 结构存储，支持按需获取历史消息
        String redisKey = getKey(conversationId);
        for (Message message : messages) {
            String jsonStr = MessageUtil.toJson(message);
            redisTemplate.opsForList().rightPush(redisKey, jsonStr);
        }
    }

    @Override
    public List<Message> get(String conversationId, int lastN) {
        String redisKey = CHAT_MEMORY_KEY_PREFIX + conversationId;
        if(lastN <= 0){
            //获取全部消息
            List<String> range = redisTemplate.opsForList().range(redisKey, 0, -1);
            List<Message> result = range.stream().map(jsonStr -> MessageUtil.toMessage(jsonStr)).toList();
            return result;
        }else {
            //获取最近的N条消息
            List<String> range = redisTemplate.opsForList().range(redisKey, -lastN, -1);
            List<Message> result = range.stream().map(jsonStr -> MessageUtil.toMessage(jsonStr)).collect(Collectors.toList());
            return result;
        }
    }

    @Override
    public void clear(String conversationId) {
        String redisKey = getKey(conversationId);
        redisTemplate.delete(redisKey);
    }

    public String getKey(String conversationId){
        return CHAT_MEMORY_KEY_PREFIX + conversationId;
    }


}
